package com.nzw.utils;

import com.nzw.common.cache.CacheType;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheException;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.aspectj.weaver.tools.cache.CacheFactory;

/**
 * 版权归
 * TODO 缓存工具类
 */
public class CacheUtil {

    public static CacheManager cacheManager;

    static {
        try {
            cacheManager = CacheManager.create(CacheFactory.class.getResource("/ehcache/ehcache.xml"));
        } catch (CacheException e) {
            e.printStackTrace();
        }
    }


    private CacheUtil() {
    }

    public static CacheManager getCacheManager() {
        return cacheManager;
    }

    /**
     * @param cacheName 缓存名
     * @return
     * @author duosheng.mo
     * @DateTime 2015-11-21 下午04:01:40
     * @serverCode 服务代码
     * @serverComment 服务注解
     */
    public static Cache getCache(String cacheName) {
        Cache cache = getCacheManager().getCache(cacheName);//"wxCache"
        return cache;
    }

    /**
     * @param cacheType 缓存名
     * @param key
     * @param value
     * @author duosheng.mo
     * @DateTime 2015-11-21 下午04:01:15
     * @serverCode 服务代码
     * @serverComment 服务注解
     */
    public static void saveKeyValue(CacheType cacheType, String key, Object value) {
        Cache cache = getCache(cacheType.getName());
        Element element = new Element(key, value);
        cache.put(element);
    }

    /**
     * @param cacheType 缓存名
     * @param key
     * @return
     * @author duosheng.mo
     * @DateTime 2015-11-21 下午04:01:30
     * @serverCode 服务代码
     * @serverComment 服务注解
     */
    public static Object getCacheValue(CacheType cacheType, String key) {
        Element ele = getCache(cacheType.getName()).get(key);
        if (ele != null) {
            return ele.getValue();
        }
        return null;
    }

    public static void removeCacheValue(CacheType cacheType, String key) {
        Cache cache = getCache(cacheType.getName());
        cache.remove(key);
    }
}
